﻿using NICWebApi.Extensions.JWT.Options;

/// <summary>
/// 通用类
/// </summary>
internal static class Utils
{
    /// <summary>
    /// 配置节名称
    /// </summary>
    internal const string OptionSection = "JWTSettings";

    /// <summary>
    /// 获取当前目录下所有Json文件
    /// </summary>
    /// <returns></returns>
    public static string[] GetJsonFiles()
    {
        var matcher = new Matcher();
        matcher.AddInclude("**/*.json");
        var jsonFiles = matcher.GetResultsInFullPath(AppContext.BaseDirectory).ToArray();
        return jsonFiles;
    }

    /// <summary>
    /// 获取Json文件配置
    /// </summary>
    /// <returns></returns>
    public static JWTSettingsOptions GetOptions()
    {
        var jsonFiles = GetJsonFiles();
        JWTSettingsOptions options = default;

        foreach (var jsonFile in jsonFiles)
        {
            try
            {
                var configuration = new ConfigurationBuilder()
                    .AddJsonFile(jsonFile, optional: false, reloadOnChange: true)
                    .Build();

                options = configuration.GetSection(OptionSection).Get<JWTSettingsOptions>();
                if (options != null)
                {
                    break;
                }
            }
            catch
            {
                // 忽略读取失败的文件
                continue;
            }
        }

        // 如果没有找到配置，返回默认配置
        return options ?? new JWTSettingsOptions();
    }
}